import time
import traceback
import os

from flask import Flask, jsonify, render_template, send_from_directory, request, session, redirect, url_for
from flask_cors import CORS  # 处理跨域请求
from pathlib import Path

from src.ADSB_preprocessing import main as pre_main
from src.pof_functions.flight_phase_finder_xplane import main as xplane_main
from src.evaluation import main as eva_main

app = Flask(__name__)
app.secret_key = 'your_secret_key_here'

CORS(app)

# 配置绝对路径
BASE_DIR = Path(__file__).parent.resolve()  # 项目根目录
IMAGE_DIR = BASE_DIR / 'results' / 'figs'  # 图片目录

print(BASE_DIR)

status_dict = {
    "pre_status": False,
    "eva_status": False,
    "images_path": None
}


# 固定账号密码
LOGIN_CREDENTIALS = {
    "username": "admin",
    "password": "123456"
}

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')

        if username == LOGIN_CREDENTIALS['username'] and password == LOGIN_CREDENTIALS['password']:
            session['logged_in'] = True
            return redirect(url_for('index'))
        else:
            return render_template('login.html', error="用户名或密码错误")

    return render_template('login.html')


@app.route('/logout')
def logout():
    session.pop('logged_in', None)
    return redirect(url_for('login'))


@app.before_request
def require_login():
    # 白名单路径不需要登录即可访问
    allowed_endpoints = ['login', 'static']
    if request.endpoint not in allowed_endpoints and not session.get('logged_in'):
        return redirect(url_for('login'))




@app.route('/')
def index():
    if not session.get('logged_in'):
        return redirect(url_for('login'))

    status_dict["pre_status"] = False
    status_dict["eva_status"] = False
    return render_template('index.html', username=LOGIN_CREDENTIALS['username'])



@app.route('/api/images')
def get_images():
    eva_status = status_dict["eva_status"]
    if not eva_status:
        return jsonify({
            "intermediate": [],
            "final": []}), 200
    try:
        # 验证目录是否存在
        if not IMAGE_DIR.exists():
            return jsonify({"error": "图片目录不存在"}), 404

        # 获取所有图片文件
        intermediate = []
        final = []
        valid_ext = {'.jpg', '.jpeg', '.png', '.webp', '.gif'}
        intermediate_images_path = status_dict["images_path"]
        if intermediate_images_path is not None:

            for file in intermediate_images_path.glob('*'):
                if file.suffix.lower() in valid_ext and file.is_file():
                    intermediate.append({
                        "filename": file.name,
                        "url": f"/intermediate_images/{file.name}",
                        "size": file.stat().st_size
                    })

        for file in IMAGE_DIR.glob('*'):
            if file.suffix.lower() in valid_ext and file.is_file():
                final.append({
                    "filename": file.name,
                    "url": f"/images/{file.name}",
                    "size": file.stat().st_size
                })

        # 按文件名排序
        intermediate.sort(key=lambda x: x['filename'])
        final.sort(key=lambda x: x['filename'])

        return jsonify({
            "intermediate": intermediate,
            "final": final})

    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.route('/images/<filename>')
def serve_image(filename):
    """图片访问路由"""
    return send_from_directory(IMAGE_DIR, filename)


@app.route('/intermediate_images/<filename>')
def serve_intermediate_image(filename):
    """中间结果图片访问路由"""
    intermediate_images_path = status_dict["images_path"]
    if intermediate_images_path is None:
        return jsonify({"error": "中间结果图片目录未设置"}), 404
    intermediate_images_path = Path(intermediate_images_path)
    if not intermediate_images_path.exists():
        return jsonify({"error": "中间结果图片目录不存在"}), 404
    return send_from_directory(intermediate_images_path, filename)


@app.route('/api/execute', methods=['POST'])
def start_execute():
    params = {
        "n_clusters": 160,
        "n_features": 7,
        "batch_size": 16,
        "weights": [0.7, 0.8, 0.1],
        "n_layers": 2,
        "learning_rate": 0.01,
        "hidden_dim": 16,
        "n_epochs": 3500,
        "alpha": 0,
        "trial": 2,
        "kmeans_iters": 100
    }
    status_dict["pre_status"] = False
    status_dict["eva_status"] = False
    try:
        folder = request.get_json().get('path')
        # csvs_path, images_path = pre_main(folder=folder)
        save_folder  = BASE_DIR / 'data/temp'
        images_path  = save_folder / 'figures'
        csvs_path  = save_folder / 'trajectories'

        is_success = xplane_main(folder, 'data/temp')
        if is_success:
            status_dict["pre_status"] = True
            status_dict["images_path"] = images_path
        time.sleep(0.1)
        params_data = eva_main(custom_data_path=csvs_path, final_params=params)
        if params_data:
            status_dict["eva_status"] = True
        return jsonify(params_data)

    except Exception as e:
        print(e)
        traceback.print_exc()
        return jsonify({"error": str(e)}), 500


@app.route('/api/status')
def get_status():
    pre_status = status_dict["pre_status"]
    eva_status = status_dict["eva_status"]
    if not pre_status:
        status = 0
    elif not eva_status:
        status = 1
    else:
        status = 2
    return jsonify({"status": status}), 200


if __name__ == '__main__':
    # 确保图片目录存在
    IMAGE_DIR.mkdir(parents=True, exist_ok=True)
    app.run(debug=True, port=5000)
